package com.tidc.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tidc.manage.constant.DatabaseField;
import com.tidc.manage.domain.Student;
import com.tidc.manage.enums.StateEnum;
import com.tidc.manage.mapper.StudentMapper;
import com.tidc.manage.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tidc.manage.service.IUserRoleService;
import com.tidc.manage.service.IUserService;
import org.apache.ibatis.javassist.NotFoundException;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 学生服务实现类
 * </p>
 *
 * @author 张朝锋
 * @author 张伟杰
 * @since 2018-09-14
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IUserService userService;

    @Override
    public StateEnum saveStudent(Student student) {
        student.setLevel(3);
        String studentId = student.getStudentId();
        if (baseMapper.selectCount(new QueryWrapper<Student>().eq(DatabaseField.STUDENT_ID, studentId)) != 0) {
            baseMapper.update(student, new QueryWrapper<Student>().eq(DatabaseField.STUDENT_ID, studentId));
            return StateEnum.UPDATE;
        } else {
            baseMapper.insert(student);
            //初始化用户权限
            userRoleService.initializeUserRoleForStudentByStudentId(student.getStudentId());
            return StateEnum.SUCCEED;
        }
    }

    @Override
    public IPage<Student> getStudentOfPage(long current, long size, Student student) {
        Page<Student> studentPage = new Page<>(current, size);
        if(student == null){
            student = new Student();
        }
        studentPage.setDesc("grade");
        return baseMapper.getStudentAllOfPage(studentPage, student);
    }

    @Override
    public Student getStudentById(String studentId) {
        Student student = baseMapper.selectById(studentId);
        student.setLevel(userRoleService.getRoleLevelByUserId(studentId));
        return student;
    }

    @Override
    public Integer deleteStudentByStudentId(String studentId) throws NotFoundException {
        // 先找找有没有这个批
        if(baseMapper.selectById(studentId) == null) {
            throw new NotFoundException("Student("+studentId+")");
        }
        // 居然找到了这个批,先把他用户给卸了
        userService.deleteUserById(studentId);
        return baseMapper.deleteById(studentId);
    }
}
